//
//  BHMeMainViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/4.
//

import UIKit

class BHMeMainViewController: BHBaseViewController {
  
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height-UIScreen.safeBottomHeight-49)
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .color_f8f8f8
        view.register(UINib.init(nibName: "BHMeRowTableViewCell", bundle: nil), forCellReuseIdentifier: "BHMeRowTableViewCell")
        return view
    }()
    
    lazy var quiteBtnView: UIView = {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 50))
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 20, y: 2.5, width: UIScreen.width-40, height: 45)
        btn.backgroundColor = .color_34CE98
        btn.setTitle("退出登录", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
        btn.addTarget(self, action: #selector(quiteAccount), for: .touchUpInside)
        btn.addLayerCorner(22.5, 0, .white)
        view.addSubview(btn)
        return view
    }()
    
    let rowsArray: [BHMeGroupItemModel] = BHMeGroupItemModel.meRowsArray
    
    lazy var headerView: BHMeHeaderView = {
        let view = BHMeHeaderView.loadFromXib()
        view.delegate = self
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHMeHeaderView.headerHeight)
        return view
    }()
    lazy var groupSecView: BHMePersonalItemGroupView = {
        let view = BHMePersonalItemGroupView.init()
        return view
    }()
    
    lazy var serviceManager: BHMeServiceManager = {
        let manager = BHMeServiceManager.init()
        return manager
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.serviceManager.personalMainService(userId: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.bh_navigationBar.removeFromSuperview()
        self.view.backgroundColor = .color_f8f8f8
        self.view.addSubview(self.tableView)
        self.tableView.tableHeaderView = self.headerView
        self.tableView.tableFooterView = self.quiteBtnView
        
        self.refreshUserInfoService()
        self.personalItemDidSelectActOberserve()
     
        self.tableView.addRefresh { [unowned self] in
            self.serviceManager.personalMainService(userId: nil)
        }
    }
    
    private func personalItemDidSelectActOberserve() {
        self.groupSecView.toolsDidSelectIndex = { (index, model) in
            if model.itemName == "钱包" {
//                BHToast.toast(text: "功能开发中，敬请期待")
                BHRouter.shared.bh_goWallet()
                return
            }
            if model.itemName == "赛事" {
                let vc = BHMyCompetitionViewController.init()
                DispatchQueue.main.async {
                    self.navigationController?.pushViewController(vc, animated: true)
                }            }
            if model.itemName == "约玩" {
                let vc = BHMyFunlistViewController.init()
                DispatchQueue.main.async {
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            if model.itemName == "收藏" {
                BHRouter.shared.bh_goUserCollection()
            }
            if model.itemName == "订单" {
                let orderVC = BHMeOrderBaseViewController.init()
                DispatchQueue.main.async {
                    self.navigationController?.pushViewController(orderVC, animated: true)
                }
            }
        }
    }
    
    @objc func quiteAccount() {
        BHCommonTool.showAlertWith(showVC: nil, title: "提示", message: "是否退出当前账号", okBtn: "立即退出", cancel: "再想想") { (quite) in
            if quite == true {
                BHMeUserInfoModel.shared.clearUser()
                BHRouter.shared.bh_gologin()
            }
        }
    }
}
extension BHMeMainViewController: BHMeHeaderViewDelegate {
    func itemViewTypeDidSelect(type: Int) {
        if type == 0 || type == 1{
            BHRouter.shared.bh_goUserList(type: type, userId: nil, businessId: nil)
        }else {
            let likeVC = BHMylikeViewController.init()
            self.navigationController?.pushViewController(likeVC, animated: true)
        }
    }
    
    func showPersonalInfoDidSelect() {
        if BHMeUserInfoModel.shared.token.isEmpty == true {
            BHRouter.shared.bh_gologin()
        }else {
            BHRouter.shared.bh_goPersonalHome(userId: nil)
        }
    }
    
    func goPersonalUserHome() {
        if BHMeUserInfoModel.shared.token.isEmpty == true {
            BHRouter.shared.bh_gologin()
        }else {
            let infoVC = BHPersonalUserInfoViewController.init()
            self.navigationController?.pushViewController(infoVC, animated: true)
        }
    }
}


extension BHMeMainViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.rowsArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return  self.groupSecView.viewHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            BHCommonTool.telAct("4009600888") { (open) in
                if open == false {
                    BHToast.toast(text: "当前设备不支持打电话")
                }
            }
        }
        if indexPath.row == 1 {
            let vc = BHCommonReportViewController.init()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        if indexPath.row == 2 {
            let vc = BHMeSettingViewController.init()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
}

extension BHMeMainViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return self.groupSecView
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHMeRowTableViewCell", for: indexPath) as! BHMeRowTableViewCell
        let model = self.rowsArray[indexPath.row]
        cell.model = model
        cell.type = indexPath.row
        cell.line.isHidden = indexPath.row == 2
        return cell
    }
}


 
extension BHMeMainViewController {
    func refreshUserInfoService() {
        self.serviceManager.responseUserInfoBlock = {[unowned self] model in
            
            self.tableView.endRefresh()
            BHMeUserInfoModel.shared.appendInfo(model: model)
            
            self.headerView.refreshUser()
        }
    }
}
